package com.diapoclic.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.diapoclic.entitybean.User;
import com.diapoclic.entitymanager.UserManager;

public class ContactServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)						
											throws IOException, ServletException{
		
		UserManager userMana = new UserManager();
		User sessionUser = new User();
		User newFriend = new User();

		////////////////////////////////UTILISATION DES COOKIES///////////////////////////
		
		sessionUser=userMana.getSessionUser(request.getCookies());

    	//////////////////////////////////LISTE DES AMIS////////////////////////////////////
    	
    	try {
			request.setAttribute("friendlist",userMana.getUserDao().listFriend(sessionUser.getIdUser()));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	///////////////////////////////////AJOUT D'UN AMI////////////////////////////////////
				
		//test et ajout des logins renseignes
    	String newfriend = (String)request.getParameter("friend");
		String res = "normal";
		if(newfriend != null)
		{	
			try {
				if(userMana.addFriend(sessionUser.getIdUser(), newfriend)) //Trouver le moyen de conna�tre le user en cours
				{
					res = "success";
					newFriend = userMana.getUserDao().findByLogin(newfriend);
					request.setAttribute("friend", newFriend);
				}
				else
					res = "fail";		
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		//////////////////////////////SUPPRIMER UN AMI///////////////////////////
		
		String supprfriend = (String)request.getParameter("suppr");
		System.out.println(supprfriend);
		
		try {
			userMana.getUserDao().removeFriend(sessionUser.getIdUser(), (userMana.getUserDao().findByLogin(supprfriend)).getIdUser());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//////////////////////ATTRIBUTION DES VARIABLES ET APPEL DE LA JSP/////////////////
		
		request.setAttribute("res", res);
		request.setAttribute("newfriend", newfriend);
		request.setAttribute("sessionuser", sessionUser);

		request.getRequestDispatcher("contacts.jsp").forward(request, response);		
	}
	
	
		
		
	public void doPost(HttpServletRequest request, HttpServletResponse response)						
											throws IOException, ServletException{
		doGet(request, response);
	}
	

}
